package com.pangu.util;

import com.pangu.util.security.SecurityUtil;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Point;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;

import java.lang.reflect.Method;
import java.math.BigInteger;
import java.security.SecureRandom;

/**
 * 与设备相关的工具类
 * <p/>
 * Created by cxlin
 */
public class DeviceUtil {

    /**
     * 判断是否是平板
     *
     * @param context
     * @return
     */
    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >=
                Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 检测是否是虚拟机
     */
    public static boolean isEmulator(Context context) {
        // 判断是否原生模拟器
        if (Build.MODEL.equalsIgnoreCase("sdk") || Build.MODEL.equalsIgnoreCase("google_sdk")) {
            return true;
        }

        // 判断是否平板和imei号为空
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String imei = tm.getDeviceId();
        if (!isTablet(context) && StringUtil.isEmptyString(imei)) {
            return true;
        }

        return false;

    }

    /**
     * 获取屏幕密度
     *
     * @param displayMetrics
     * @return
     */
    public static int getDensityDpi(DisplayMetrics displayMetrics) {
        int density = 160;
        try {
            density = displayMetrics.getClass().getField("densityDpi").getInt(displayMetrics);

        } catch (Throwable e) {
            e.printStackTrace();

        }

        return density;
    }

    /**
     * 获取硬件架构
     *
     * @return
     */
    public static String getCpuAbi() {
        if(Build.VERSION.SDK_INT < 21){
            // 硬件架构
            String abi = Build.CPU_ABI;
            abi = (abi == null || abi.trim().length() == 0) ? "" : abi;
            // 检视是否有第二类型
            String cpuAbi2 = null;
            try {
                cpuAbi2 = Build.class.getField("CPU_ABI2").get(null).toString();

            } catch (Throwable e) {
                e.printStackTrace();

            }
            cpuAbi2 = (cpuAbi2 == null || cpuAbi2.trim().length() == 0) ? null : cpuAbi2;
            if (cpuAbi2 != null) {
                abi = abi + "|" + cpuAbi2;
            }

            return abi;

        } else{
            StringBuilder abi = new StringBuilder();
            String[] supportedAbis = Build.SUPPORTED_ABIS;
            if (supportedAbis != null && supportedAbis.length > 0) {
                for (int i = 0; i < supportedAbis.length; ++i) {
                    if (i == (supportedAbis.length - 1)) {
                        abi.append(supportedAbis[i]);

                    } else {
                        abi.append(supportedAbis[i]).append("|");
                    }
                }
            }

            return abi.toString();
        }
    }

    /**
     * 获得系统属性
     * <p/>
     * 通过反射SystemProperties获得
     *
     * @param key
     * @return
     */
    public static String getSystemPropertie(String key) {
        String value = null;
        try {
            Class<?> mClassType = Class.forName("android.os.SystemProperties");
            Method mGetMethod = mClassType.getDeclaredMethod("get", String.class);
            value = (String) mGetMethod.invoke(mClassType, key);

        } catch (Throwable e) {
            e.printStackTrace();
        }

        return value;
    }

    /**
     * 判断是不是MIUI系统
     *
     * @return
     */
    public static boolean checkMIUISystem() {
        String miuiName = getSystemPropertie("ro.miui.ui.version.name");
        String miuiCode = getSystemPropertie("ro.miui.ui.version.code");
        // 只要其中一个不为空字符串就判断为是miui系统
        // [ro.miui.ui.version.code]: [3]
        // [ro.miui.ui.version.name]: [V5]
        if (!StringUtil.isEmptyString(miuiName) || !StringUtil.isEmptyString(miuiCode)) {
            return true;

        } else {
            return false;

        }
    }

    /**
     * 依据传入的imei与mac生成唯一标识
     *
     * @param context
     * @param imei
     * @param mac
     * @return
     */
    public static String createUuid(Context context, String imei, String mac) {
        String rwaStr = (imei == null ? "" : imei) + (mac == null ? "" : mac);
        String md5Str = SecurityUtil.md5Encode(rwaStr);

        if (md5Str.length() > 15) {
            md5Str = md5Str.substring(0, 16);

        } else {
            md5Str = "0000000000000000";
        }

        SecureRandom random = new SecureRandom();
        String randomStr = new BigInteger(64, random).toString(16);

        String userUuidStr = md5Str + randomStr;

        return userUuidStr;
    }

    /**
     * 如：
     * values-sw540dp-w800dp里的<br>
     * sw540dp部分<br>
     *
     * @param configValue
     */
    public static final int computeDisplaySW(int configValue) {
        return configValue / 4096;

    }

    /**
     * 如：
     * values-sw540dp-w800dp里的<br>
     * w800dp部分<br>
     *
     * @param configValue
     */
    public static final int computeDisplayW(int configValue) {
        return configValue % 4096;

    }

    /**
     * dip转px
     *
     * @param context
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        // 密度因子
        float scale = getDpi(context) / 160;// 等于 scale=dm.density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * px转dip
     *
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        // 密度因子
        float scale = getDpi(context) / 160;// 等于 scale=dm.density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static float getDpi(Context context) {
        // 获取当前屏幕
        DisplayMetrics dm = new DisplayMetrics();
        // 返回当前资源对象的DispatchMetrics信息。
        dm = context.getApplicationContext().getResources().getDisplayMetrics();
        // 设置DensityDpi
        return dm.densityDpi;
    }

    /**
     * 获取当前屏幕宽度PX值(分辨率)
     *
     * @param activity
     * @return
     */
    public static int getDisplayWidthPX(Activity activity) {
        Point outSize = new Point();
        activity.getWindowManager().getDefaultDisplay().getSize(outSize);
        int displayWidthPX = outSize.x;
        return displayWidthPX;

    }

    /**
     * 获取当前屏幕高度PX值(分辨率)
     *
     * @param activity
     * @return
     */
    public static int getDisplayHeightPX(Activity activity) {
        Point outSize = new Point();
        activity.getWindowManager().getDefaultDisplay().getSize(outSize);
        int displayHeightPX = outSize.y;
        return displayHeightPX;
    }

    /**
     * 获取版本号
     * @param context
     * @return
     */
    public static String getAppVersion(Context context){
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取 android id
     * @param context
     * @return
     */
    public static String getAndroidID(Context context){
        String androidID = null;
        try {
            androidID = Settings.Secure.getString(context.getContentResolver(),"android_id");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return androidID;
    }

    /**
     * 获取 android 设备id
     * @param context
     */
    public static String getIMEI(Context context){
        String imei = null;
        try {
            TelephonyManager telephonyManager = ((TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE));
            imei = telephonyManager.getDeviceId();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return imei;
    }
}
